package cn.kbyue.ormdemo.generate;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.TemplateType;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.fill.Column;
import com.baomidou.mybatisplus.generator.fill.Property;
import com.baomidou.mybatisplus.generator.keywords.MySqlKeyWordsHandler;

import java.util.Collections;

/**
 * @author xlang
 * @date 2023/4/12 11:29
 */
public class MybatisPlusGenerator {

    private static final String URL = "jdbc:mysql://127.0.0.1:3306/springboot-demo?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8&allowMultiQueries=true&autoReconnect=true";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "root";

    public static void main(String[] args) {
        new MybatisPlusGenerator().generator();
    }

    public void generator() {
        FastAutoGenerator.create(URL, USERNAME, PASSWORD)
                .globalConfig(builder -> {
                    builder.author("kbyue") // 设置作者
                            // .enableSwagger() // 开启 swagger 模式
                            .outputDir("D:\\project\\framework-demo\\orm-demo\\src\\main\\java\\"); // 指定输出目录
                })
                .dataSourceConfig(builder -> builder
                        // .typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
                        //     int typeCode = metaInfo.getJdbcType().TYPE_CODE;
                        //     if (typeCode == Types.SMALLINT) {
                        //         // 自定义类型转换
                        //         return DbColumnType.INTEGER;
                        //     }
                        //     return typeRegistry.getColumnType(metaInfo);
                        // })
                        .dbQuery(new MySqlQuery())
                        .typeConvert(new MySqlTypeConvert())
                        .keyWordsHandler(new MySqlKeyWordsHandler())
                )
                .packageConfig(builder -> {
                    builder
                            .parent("cn.kbyue") // 设置父包名, 和 outputDir 配合使用
                            .moduleName("ormdemo") // 设置父包模块名
                            .entity("entity")
                            .service("service")
                            .serviceImpl("service.impl")
                            .mapper("mapper")
                            .controller("controller")
                            // 设置mapperXml生成路径
                            .pathInfo(Collections.singletonMap(OutputFile.xml, "D:\\project\\framework-demo\\orm-demo\\src\\main\\resources\\mapper"));
                })
                .templateConfig(builder -> {
                    builder
                            // 禁止生成的模板
                            .disable(TemplateType.CONTROLLER)
                            // 模板文件路径
                            // .entity("/templates/entity.java")
                            // .controller("/templates/controller.java")
                    ;
                })
                .injectionConfig(builder -> {
                    builder
                            // 输出文件之前的操作
                            .beforeOutputFile(((tableInfo, objectMap) -> {
                                System.out.println("tableInfo: " + tableInfo.getEntityName() + " objectMap: " + objectMap.size());
                            }))
                            // 自定义 注入Map
                            // .customMap(Collections.singletonMap("test", "baomidou"))
                            // 自定义模板文件
                            // .customFile(Collections.singletonMap("test.txt", "/templates/test.vm"))
                    ;
                })
                .strategyConfig(builder -> {
                    builder
                            // 设置需要生成的表名
                            .addInclude("orm_person")
                            // 设置过滤表前缀
                            .addTablePrefix("orm_")
                            // 实体配置
                            .entityBuilder().enableLombok().enableChainModel().enableActiveRecord()
                            .enableTableFieldAnnotation()
                            .versionColumnName("version").versionPropertyName("version")
                            .logicDeleteColumnName("deleted").logicDeletePropertyName("deleted")
                            .columnNaming(NamingStrategy.underline_to_camel)
                            .addTableFills(new Column("createTime", FieldFill.INSERT))
                            .addTableFills(new Property("updateTime", FieldFill.INSERT_UPDATE))
                            .idType(IdType.AUTO)
                            .disableSerialVersionUID()
                            .enableFileOverride();
                })
                // 使用Freemarker引擎模板，默认的是Velocity引擎模板
                .templateEngine(new FreemarkerTemplateEngine())
                .execute();
    }

}
